/**
 * FileName: FloatInterpreter
 * Author:   zhaoxiaoqiang
 * Date:     2019/8/20 14:20
 * Description: 解析float数据
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.zxq.factory.decoder.impl;


import com.zxq.factory.decoder.IFieldDecoder;


/**
 * 〈解析float数据〉
 *
 * @author zhaoxiaoqiang
 * @date 2019/8/20
 * @since 1.0.0
 */

public class FloatDecoder implements IFieldDecoder<Float> {

    IntDecoder intDecoder = new IntDecoder();
    @Override
    public Float decoder(byte[] msg) {
       if(msg.length != 4) {
           System.out.println("Float 只支持32字节");
           return 0.0f;
       }
       //正负数标记
       Integer mark = 1;
       byte shiftExponent = 0;
      // log.info("head: " + HexBin.encode(new byte[]{msg[0]}));
       if(msg[0] < 0) {
           mark = -1;
       }

       shiftExponent = (byte) (msg[0] << 1);


       //第二个字节首位，是阶码位。第二个字节 < 0,阶码要 + 1.且需要去掉 这个首字节1
       if(msg[1] < 0) {
           shiftExponent += 1;
           msg[1] = (byte) (msg[1] & 0x7F);
       }

       byte exponentByte = 0;
       Double frameShift = (Math.pow(2,7) - 1);
       exponentByte = (byte) (shiftExponent - frameShift.intValue()) ;

       Integer exponent = Integer.valueOf(exponentByte);
      // log.info("exponent:" + exponent);
       byte[] tailBuff = new byte[3];
       for(int  i = 0; i < 3; i++) {
           tailBuff[i] = msg[i + 1];
       }

       // log.info("tail:" + HexBin.encode( tailBuff));

        Integer tailValue = intDecoder.decoder(tailBuff);

        //小数点右后，原来int值，变化成的float数值,1.xxx * Math.pow(2,exponent)中的 1.xxx的值
        Double ratioValue = tailValue * Math.pow(2, -23) + 1;
       // log.info("ratio value:" + ratioValue);
        Double floatValue = mark * Math.pow(2,exponent) * ratioValue;

        return floatValue.floatValue();
    }


//    public static void main(String[] args) {
//        Float fValue = -124.09375f;
//        log.info("float Value: " + fValue);
//        log.info( "encoder------------------------");
//        FloatFieldEncoder floatFieldEncoder = new FloatFieldEncoder();
//        byte[] hex = floatFieldEncoder.encoder(fValue,4);
//        log.info( "decoder------------------------");
//        FloatDecoder floatDecoder = new FloatDecoder();
//        Float fMsg =  floatDecoder.decoder(hex);
//        log.info("fValue:" + fMsg);
//    }



}
